#include <iostream>
#include <map>
#include <mutex>
#include <thread>

std::mutex mtx;  // 普通锁
std::map<int, int> data;  // 模拟共享资源

void Flush(bool alreadyLocked) {
    if (!alreadyLocked) {
        std::lock_guard<std::mutex> lock(mtx);
        std::cout << "Flush: Acquired lock\n";

        for (const auto& [key, value] : data) {
            std::cout << "Key: " << key << ", Value: " << value << "\n";
        }

        data.clear();
        std::cout << "Flush: Cleared data\n";
    } else {
        // 锁已经在外部持有
        std::cout << "Flush: Already locked externally\n";

        for (const auto& [key, value] : data) {
            std::cout << "Key: " << key << ", Value: " << value << "\n";
        }

        data.clear();
        std::cout << "Flush: Cleared data\n";
    }
}

void AddDataAndFlush() {
    std::lock_guard<std::mutex> lock(mtx);
    std::cout << "AddDataAndFlush: Acquired lock\n";

    data[1] = 100;
    data[2] = 200;

    Flush(true);  // 告诉 Flush 函数锁已经持有
}

int main() {
    std::thread t1(AddDataAndFlush);
    t1.join();
    return 0;
}
